// 运行时配置
import React, { useCallback } from "react";
import { RunTimeLayoutConfig, RequestConfig, useModel } from "@umijs/max";
import routes, {whiteList} from '../config/routes';
import { requestSetting } from '@/utils/requestSetting';
import RightContent from '@/components/Layout/RightContent';
import logo from '@/assets/logo/logon_name.png';
import './app.less';
import { getStorage } from "./utils/storage";

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ userId: string, title: string }> {
  const token = getStorage('token');
  if (token) {
    return { userId: '@umijs/max', title: 'login' };
  }
  return { userId: '@umijs/max', title: 'noLogin' };
}


export const request: RequestConfig = {
  ...requestSetting
};

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  const { userInfo } = useModel('userModel');

  const fetchMenuData = useCallback(() => {
    
    if (!userInfo || !userInfo?.menus?.[0]?.menus?.length) {
      // 如果没有登录则返回白名单路由
      return whiteList
    }
    // 将后端返回的路由进行组装
    const arr: any [] = [];
    const composeMenus = (list: any [], menus: any []) => {
      menus.forEach((menu: any) => {
        const item = {
          ...menu,
          menus: [],
          routes: []
        }
        if (menu?.menus?.length > 0) {
          composeMenus(item.routes, menu?.menus);
        }
        list.push(item);        
      });
    }
    composeMenus(arr, userInfo?.menus?.[0]?.menus);
    return arr;
  }, [JSON.stringify(userInfo), JSON.stringify(whiteList)]);

  // layout 配置， 具体配置项见 https://procomponents.ant.design/components/layout
  return {
    title: '',
    logo: logo,
    
    layout: 'mix',
    fixedHeader: true,
    // 默认布局调整
    rightContentRender: () => <RightContent />,
    contentStyle: {padding: 0, },
    menuDataRender: fetchMenuData
  };
};
